package com.ruoyi.epidemic.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.epidemic.service.RequiredWxOauth2;
import me.chanjar.weixin.cp.api.impl.WxCpOAuth2ServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.apache.xmlbeans.impl.jam.internal.elements.SourcePositionImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Objects;

public class ZtWxInterceptor implements HandlerInterceptor {

    @Value("${wechat.cp.corpId}")
    private String corpId;

    @Value("${wechat.cp.appConfigs.agentId}")
    private Integer agentId;

    @Value("${wechat.cp.appConfigs.secret}")
    private String secret;

    @Value("${wechat.cp.appConfigs.token}")
    private String token;

    @Value("${wechat.cp.appConfigs.aesKey}")
    private String aesKey;

    public WxCpServiceImpl getWxCpServiceImpl(){
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setCorpId(corpId);      // 设置微信企业号的appid
        config.setCorpSecret(secret);  // 设置微信企业号的app corpSecret
        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);
        return wxCpService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession();
            if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RequiredWxOauth2 annotation = method.getAnnotation(RequiredWxOauth2.class);
            try {
                if (annotation != null) {
                    String userId = (String) session.getAttribute(Constants.USER_ID);
                    if (!StringUtils.isEmpty(userId)) {
                        return true;
                    }
                    String code = request.getParameter("code");
                    if (StringUtils.isEmpty(userId) && !StringUtils.isEmpty(code)) {
                        WxCpServiceImpl wxCpService2 = this.getWxCpServiceImpl();
                        WxCpOAuth2ServiceImpl wxCpOAuth2Service = new WxCpOAuth2ServiceImpl(wxCpService2);
                        WxCpOauth2UserInfo getUserInfoOut = wxCpOAuth2Service.getUserInfo(agentId, code);
                        System.out.println("getUserInfoOut:"+getUserInfoOut);
                        WxCpOauth2UserInfo ifnull = new WxCpOauth2UserInfo();
                        if (!getUserInfoOut.equals(ifnull)) {
                            //获取微信用户ID
                            String wxUserId = getUserInfoOut.getUserId();
                            //查询对应用户表
//                            User user=new User();
//                            User user = userServiceImpl.selectOne(new QueryWrapper<User>().eq("WX_USER_ID", wxUserId));
                            //若用户表中无该微信用户，则跳转错误页面
//                            if (user == null) {
//                                response.sendRedirect(errorurl);
//                                return false;
//                            }
                            session.setAttribute(Constants.USER_ID, getUserInfoOut.getUserId());
                        }
                        return true;
                    }
//                        String url = request.getRequestURL() + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
                        String url = request.getRequestURL()  + (request.getQueryString() == null ? "" : "?" + request.getQueryString());
                        if (StringUtils.isEmpty(userId)) {
                            WxCpServiceImpl wxCpService2 = this.getWxCpServiceImpl();
                            WxCpOAuth2ServiceImpl wxCpOAuth2Service = new WxCpOAuth2ServiceImpl(wxCpService2);
                            String oauth2url = wxCpOAuth2Service.buildAuthorizationUrl(url, "","snsapi_base");
                            response.sendRedirect(oauth2url);
                            return false;
                        }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            }
            return true;
    }

}
